package com.zhouzi.zhaoyang.util;

import android.media.MediaPlayer;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Player {
    private ExecutorService mExecutorService;

    public Player() {
        mExecutorService = Executors.newSingleThreadExecutor();
    }

    public void playFile(String videoFile) {
        mExecutorService.execute(() -> {
            MediaPlayer mediaPlayer = new MediaPlayer();
            CountDownLatch countDownLatch = new CountDownLatch(1);
            try {
                FileInputStream fis = new FileInputStream(videoFile);
                mediaPlayer.setDataSource(fis.getFD());
                fis.close();
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(it -> mediaPlayer.start());
                mediaPlayer.setOnCompletionListener(it -> {
                            mediaPlayer.release();
                            countDownLatch.countDown();
                        }
                );
            } catch (IllegalArgumentException | IllegalStateException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                countDownLatch.countDown();
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
